package com.stwitinc.redmine;


import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.stwitinc.Logger;

public class RedmineCommonUtil
{
	
	//public static int informForTooManyTasks_Thread_Interval = 1800000;//30分钟
	
	public static int informForTooManyTasks_Thread_Interval = 30000;//半分钟
	
	public static Date lastInformForTooManyTasksTime=new Date();
	
	public static int time1=9;
	
	public static int time2=17;
	
	public void encrypt(String str){
			//return 
	}
	
	//从大到小排列
	public static JSONArray jsonSortByInteger(JSONArray jsonArray, String key){
		int i=0;
		for(int j=0;j<jsonArray.size();j++){
			JSONObject temp=jsonArray.getJSONObject(j);
			int iTemp=Integer.parseInt(temp.getString(key));
			i=j-1;
			
			while(i>=0 &&Integer.parseInt( jsonArray.getJSONObject(i).getString(key))<iTemp){
				jsonArray.set(i+1, jsonArray.getJSONObject(i));
				i=i-1;
			}
			
			jsonArray.set(i+1, temp);
		}
		
		
		return jsonArray;
	}

	public static String ReadFile(String Path)
	{
		BufferedReader reader = null;
		String laststr = "";
		try
		{
			FileInputStream fileInputStream = new FileInputStream(Path);
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while ((tempString = reader.readLine()) != null)
			{
				laststr += tempString;
			}
			reader.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if (reader != null)
			{
				try
				{
					reader.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		return laststr;
	}

	public  JSONArray getUserArray(){
		String userDataPath="user.json";
		String jsonContent=RedmineCommonUtil.ReadFile(userDataPath);
		
		//String jsonContent  = getClass().getClassLoader().getResource("/user.json").getPath() ;  
		
		Logger.getLogger().info(jsonContent);
		
		JSONArray jsonArray= JSON.parseArray(jsonContent);
		
		if(jsonArray==null) return null;
		
		return jsonArray;
	}
	
	public JSONObject getUserById(String id){
		JSONArray array=this.getUserArray();
		if (array==null) return null;
		
		for(int i=0;i<array.size();i++){
			JSONObject user=array.getJSONObject(i);
			if(user!=null && user.getString("id").equals(id)){
				return user;
			}
		}
		return null;
	}
	
}
